import { ACTION_TYPE, IAction, IState, ITodo } from '../../typings';

function todoReducer(state: IState, action: IAction): IState {
  const { type, payload } = action;

  switch (type) {
    case ACTION_TYPE.ADD_TODO:
      //新增一项
      return {
        ...state,
        //payload 有可能是ITodo对象 也有可能是id
        todoList: [payload as ITodo, ...state.todoList]
      };
    //删除某一项
    case ACTION_TYPE.REMOVE_TODO:
      //新增一项
      return {
        ...state,
        todoList: state.todoList.filter((todo) => todo.id !== payload)
      };
    case ACTION_TYPE.TOGGLE_TODO:
      //修改一项里面的内容
      return {
        ...state,
        todoList: state.todoList.map((todo) => {
          return todo.id === payload
            ? {
                ...todo,
                completed: !todo.completed
              }
            : {
                ...todo
              };
        })
      };
    case ACTION_TYPE.INIT_TODOLIST:
      //初始化todoList数据(localStorage)
      //将localStorage拿到的todoList赋值给state状态里的todoList
      return {
        ...state,
        todoList: payload as ITodo[]
      };
    default:
      return state;
  }
}

export { todoReducer };
